﻿
//页面回退不刷新
$(function() {
	var isPageHide = false;
	window.addEventListener('pageshow', function() {
		if(isPageHide) {
			window.location.reload();
		}
	});
	window.addEventListener('pagehide', function() {
		isPageHide = true;
	});
});
//获取sessionStorage中用户信息
var openid = sessionStorage.getItem("openid");
var user_detail = sessionStorage.getItem("user_detail");
if(typeof user_detail == 'string') {
	user_detail = JSON.parse(user_detail);
}
//TODO 测试使用，后删除掉
//openid = 'oC9QFvx2vZDcGwG1iFq3lfmaLYVA';
//获取code
var wechat_code = getQueryString('code');
if(!isNotNull(openid) && !isNotNull(wechat_code)) {
	//获取当前页面的url，并存放到session中
	var is_redirect = window.location.href;
	//	var is_redirect =  'http://www.everydaytech.cn/';
	sessionStorage.setItem("is_redirect", is_redirect);
	var url = getAuthorize('snsapi_userinfo');
	window.location.href = url;
} else if(!isNotNull(openid) && isNotNull(wechat_code)) {
	//发送请求获取access_token和openid
	try {
		getOpenId(wechat_code);
	} catch(e) {
		console.error(e);
		//popWindow(2,'网络加载异常，请刷新后重新尝试');
	}
}

function getOpenId(wechat_code) {
	$.ajax({
		type: "get",
		async: false,
		url: "http://www.everydaytech.cn:1051/api/WinXin/wechatuser?code=" + wechat_code,
		success: function(msg) {
			var result = msg;
			if(result.success) {
				var userInfo = result.data;
				openid = userInfo.openid;
				//将openid放入session
				sessionStorage.setItem("openid", openid);
				sessionStorage.setItem("drawprizeNum",userInfo.drawprizeNum);
			}

		}
	});
}

//snsapi_base or snsapi_userinfo 
function getAuthorize(scope) {
	var is_redirect = sessionStorage.getItem('is_redirect');
	var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf93b3f05b2862089&redirect_uri=' + encodeURI(is_redirect) + '&response_type=code&scope=';
	url += scope;
	url += '&state=STATE#wechat_redirect';
	return url;
}

function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return(r[2]);
	return null;
}

function isNotNull(str) {
	if(typeof str == 'undefined' || str == '' || str == null) {
		return false;
	}
	return true;
}